package com.example.systemend.Interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.systemend.pojo.User;
import com.example.systemend.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;

/**
 * @author 权哥
 * @version 1.0
 * @date 2022/6/9 22:37
 */
//登录拦截器
public class LoginInterceptor implements HandlerInterceptor {

    /***
     * 在请求处理之前进行调用(Controller方法调用之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("==========================================");
        System.out.println("当前路径："+request.getRequestURL());
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");
        String token = request.getHeader("Authorization"); //前端vue将token添加在请求头中

        if(token != null){
            System.out.println("Header的token存在");
            boolean result = JwtUtil.checkToken(token);
            if(result){
                System.out.println("通过token拦截器");
                return true;
            }
        }else {
            System.out.println("Header的token不存在!!!");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try{
                JSONObject json = new JSONObject();
                json.put("msg","token 认证失败，请重新登录");
                json.put("code","500");
                response.getWriter().append(json.toJSONString());
                System.out.println("认证失败，未通过拦截器");

            }catch (Exception e){
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
        }
        return false;
    }


    /***
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("执行了拦截器的postHandle方法");
    }

    /***
     * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("执行了拦截器的afterCompletion方法");
    }

}
